"use client";
import React, { useState, useEffect } from "react";
import Modal from "react-modal";
import Content from "@/components/content";
import MyCover from "@/components/myCover";
import LabelValue from "@/components/labelValue";
import List from "@/components/list";
import styles from "./index.module.scss";
import { getLocalStorage, setLocalStorage, clearAllLocalStorage, getLocalUserInfo } from "@/utils/localStorage";
import EditUser from "@/components/editUser";
import { userServer } from "@/api";
import moment from "moment";
import { useStore } from '@/store';
import Login from "@/components/login"
import { Button } from '@arco-design/mobile-react';

interface MyPorps {
}

interface UserInfoProps{
  [key: string]: any
}
const randomFn = () => Math.ceil(Math.random() * 1000);

const My: React.FC<MyPorps> = () => {
  const [userInfo, setUserInfo] = useState<UserInfoProps>({});
  const [loginVisible, setLoginVisible] = React.useState<boolean>(false);
  const [collects, setCollects] = useState<Array<any>>([]);
  const [reports, setReports] = useState<Array<any>>([]);

  useEffect(() => {
    try {
      const _USER : string | null= getLocalStorage('userInfo')
      const user = _USER ? JSON.parse(_USER) : {};
      if(user?.id){
        setLoginVisible(false)
        setUserInfo(user);
        queryReportsByUserId(`${user.id}`);
      } else {
        setLoginVisible(true)
      }
    } catch (error) {
      console.log(error);
    }
  }, [userInfo?.id]);






  const queryCollectByUserId = async (userId: string) => {
    try {
      const {code, data, message} = await userServer.findColloectByUserId({userId});
      console.log('code, data, message', code, data, message)
      if(code === 200 && Array.isArray(data)){
        console.log('查询成功')
        const _r = data.map(item => {
          item.txt = item.startLocation;
          item.time = item.endLocation;
          return item;
        })
        setCollects(data)
      } else {
        console.log('查询失败')
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 通过用户id查举报了哪些
  const queryReportsByUserId = async (userId: string) => {
    try {
      const {code, data, message} = await userServer.findReportByUserId({userId});
      if(code === 200 && Array.isArray(data)){
        console.log('查询成功')
        const _r = data.map(item => {
          item.txt = item.reportContent
          item.time = item.reportTime ? moment(item.reportTime).format("YYYY-MM-DD") : ''
          return item;
        })
        setReports(_r);
        queryCollectByUserId(userId); // todo 放在一起通过await 执行，接口会认为是统一接口，会拦截暂时先这样处理， 不影响功能
      } else {
        console.log('查询失败')
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 判断用户是否已经登录，并且判断是乘客还是司机
  const queryLoginUserInfo = () => {
    const res = getLocalUserInfo();
    console.log('退出之后会有信息吗', res)
    const isEmpt = (v:any) => v === null || v === undefined || v === "";
    return res && !isEmpt(res)
  }



  // 通过用户id查收藏了哪些
  
  // 修改用户信息
  const updateUserInfo = async (formData:any) => {
    try {
      const userId = Object.keys(userInfo).includes('id') ? userInfo.id : undefined
      if(!userId){
        alert("没有用户id")
        return;
      }
      const { code, data, message } = await userServer.putUser({ id: userId, data:formData});
      if (code === 200) {
        setLocalStorage('userInfo', JSON.stringify(data));
        setUserInfo(data);
        setIsOpen(false)
        alert('修改用户信息成功');
      } else {
        alert('修改用户信息失败');
        setIsOpen(false)
      }
    } catch (error) {
      console.log(error);
    }
  };




  const baseInfo = [
    {
      label: "呢称:",
      value: userInfo?.nickname || "",
    },
    {
      label: "用户名:",
      value: userInfo?.username || "",
    },
    {
      label: "手机号:",
      value: userInfo?.phone || "",
      icon: userInfo?.phone ? "fa-solid fa-phone" : "",
    },
    {
      label: "邮箱:",
      value: userInfo?.email || "",
      icon: userInfo?.email ? "fa-regular fa-envelope" : "",
    },
    {
      label: "车牌:",
      value: userInfo?.carNum ? userInfo?.carNum : "",
      icon: userInfo?.carNum ? "fa-solid fa-car" : "",
    },
  ];


  const [isOepn, setIsOpen] = useState<boolean>(false);
  const closeModal = () => setIsOpen(false);

  const customStyles = {
    content: {
      top: "0",
      left: "0",
      right: "0",
      bottom: "0",
      // marginRight: '-50%',
      // transform: 'translate(-50%, -50%)',
      background: "rgba(0,0,0,.5)",
    },
  };

  const loginModalCustomStyles = {
    content: {
      top: '0',
      left: '0',
      right: '0',
      bottom: '0',
      background:'rgba(0,0,0,.5)',
      display: "flex",
      justifyContent: "center",
      alignItems: "center"
    }
  }

  type OnLogin = (data: {userName: string, password: string}) => void
  const onLogin : OnLogin= (data) => {
    console.log("onLoginhttp", data)
    setLoginVisible(false)  
    window.location.reload()
  }



  const logout = async () => {
    clearAllLocalStorage();
    console.log('window.location.href',window.location.href)
    const path = window.location.origin + '/car'
    window.location.replace(path);
  }

  return (
    <Content className={`${styles["my-componet"]}`}>
      <div>    
        <Modal
          isOpen={isOepn}
          onRequestClose={closeModal}
          style={customStyles}
          // appElement={document.querySelector('body')}
        >
          <EditUser onClose={() => setIsOpen(false)} title={"修改用户信息"} getFormData={updateUserInfo}/>
        </Modal>

        <Modal
        isOpen={loginVisible}
        onRequestClose={() => setLoginVisible(false)}
        style={loginModalCustomStyles}
        // appElement={document.querySelector('body')}
      >
        <Login title="登录/注册" onClose={() => setLoginVisible(false)} onOk={onLogin} onlySubmit={false}/>
      </Modal>



        <div className={`${styles["wrap-info"]}`}>
          <MyCover
            nickname={userInfo?.nickname || ""}
            signature={userInfo?.signature || ""}
            openEdit={() => setIsOpen(true)}
          />
         <React.Fragment>

                    <div className={styles["block"]}>
                                {baseInfo.map((info, i) => (
                                  <LabelValue
                                    label={info.label}
                                    value={info.value}
                                    icon={info.icon}
                                    key={i}
                                  />
                                ))}
                              </div>
                              <div className={`${styles["space-bt-20"]}`}>
                                <List
                                  list={collects}
                                  title={"我的收藏"}
                                  more={() => console.log("更多")}
                                />
                              </div>
                              <div className={`${styles["space-bt-20"]}`}>
                                <List
                                  list={reports}
                                  title={"我的举报"}
                                  more={() => console.log("更多")}
                                />
                              </div>
                              <div
                                className={`${styles["space-bt-20"]} ${styles["padding-bot-70"]}`}
                              >
                                {/* <List
                                  list={record}
                                  title={"我的乘车记录"}
                                  more={() => console.log("更多")}
                                /> */}
                              </div>
                              <div className={`${styles['my-login']}`} onClick={logout}>退出登录</div>

                              <Button type="primary">按钮</Button>
             </React.Fragment>
          {/* {
             !queryLoginUserInfo() &&  <div className={`${styles["not-logged"]}`}>您还未登录，请登录后发布信息</div>
          } */}
         
        </div>
     
      </div>
    </Content>
  );
};

export default My;
